package com.wanho.java159.common.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

@Component
public class FreeMarkerUtil {
    /** 配置对象*/
    private  Configuration configuration;
    @Value("${freemarker.template_dir_path}")
    private String templateDirPath ;

    @Value("${freemarker.target_dir_path}")
    private String targetDirPath ;


    /**
     * 创建 Freemarker 模板对象
     * @return  返回 Freemarker 模板对象
     */
    private  synchronized Configuration getInstance() {
        //保证 创建 单例的 configuration对象
        if (null == configuration) {
            //设置 freemarker版本
            configuration = new Configuration(Configuration.VERSION_2_3_23);
            try {
                //设置模板目录
                configuration.setDirectoryForTemplateLoading(new File(templateDirPath));
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 设置语言编码
            configuration.setEncoding(Locale.CHINA, "utf-8");
        }
        return configuration;
    }

    /**
     * 生成 html 代码
     * @param ftl
     * @param dataMap
     */
    public void genHtml(String ftl, Map<String,Object> dataMap){
        System.out.println("======FreeMarkerUtil========genHtml======begin==");
        try {
            this.configuration = getInstance() ;
            // 根据模板名获得模板对象
            Template template = configuration.getTemplate(ftl);
            // 填充数据
            FileOutputStream fos = new FileOutputStream(targetDirPath+dataMap.get("id")+".html");
            OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
            BufferedWriter bw = new BufferedWriter(osw, 1024);
            template.process(dataMap, bw);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        System.out.println("======FreeMarkerUtil========genHtml======end==");
    }
}
